package com.asurplus.weixin.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.asurplus.weixin.utils.WeiXinConst;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lizhou
 * @since 2020-10-13
 **/
@Api(tags = "微信端--用户授权")
@Controller
@RequestMapping("weixin")
public class WeiXinAuthController {

    /**
     * QQ互联中提供的 appid 和 appkey
     */
    @Value("${weixin.appid}")
    public String APPID;
    @Value("${weixin.appsecret}")
    public String APPKEY;
    @Value("${weixin.callback}")
    public String URL;

    /**
     * 请求授权页面
     */
    @RequestMapping("auth")
    public String token(HttpSession session) throws Exception {
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state", uuid);

        // Step1：获取Authorization Code
        return "redirect:" + WeiXinConst.AUTHORIZATION_CODE.replace("APPID", APPID).replace("REDIRECTURI", URLEncoder.encode(URL, "utf-8")).replace("STATE", uuid);
    }

    /**
     * 授权回调
     */
    @GetMapping(value = "callback")
    public String callback(HttpServletRequest request) throws Exception {
        HttpSession session = request.getSession();
        // 得到Authorization Code
        String code = request.getParameter("code");
        // 我们放在地址中的状态码
        String state = request.getParameter("state");
        String uuid = (String) session.getAttribute("state");

        // 验证信息我们发送的状态码
        if (null != uuid) {
            // 状态码不正确，直接返回登录页面
            if (!uuid.equals(state)) {
                return "redirect:login";
            }
        }

        // Step2：通过Authorization Code获取Access Token
        JSONObject resJson = JSONObject.parseObject(HttpUtil.get(WeiXinConst.ACCESS_TOKEN.replace("APPID", APPID).replace("SECRET", APPKEY).replace("CODE", code)));
        if (null == resJson) {
            return "redirect:login";
        }
        String accessToken = resJson.getString("access_token");
        String openId = resJson.getString("openid");
        if (StringUtils.isBlank(accessToken) || StringUtils.isBlank(openId)) {
            return "redirect:login";
        }

        // Step3: 获取微信用户信息
        resJson = JSONObject.parseObject(HttpUtil.get(WeiXinConst.USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId)));
        System.out.println(resJson);
        if (null == resJson) {
            return "redirect:login";
        }
        return "redirect:/";
    }
}
